import {
    UPLOAD_INFO,
    ALLOWEB_TYPE,
    CHUNK_SIZE,
    API
} from './config'
    ; (function (doc) {
        const oProgress = doc.querySelector('#uploadProgress');
        const oUploader = doc.querySelector('#videoUploader');
        const oInfo = doc.querySelector('#uploadInfo');
        const oBtn = doc.querySelector('#uploadBtn');
        let uploadedSize = 0;
        let uploadedResult = null;
        const init = () => {
            bindEvents();
        }

        function bindEvents() {
            oBtn.addEventListener('click', uploadVideo, false);
        }

        async function uploadVideo(e) {
            const { files: [file] } = oUploader;
            if (!file) {
                oInfo.innerText = UPLOAD_INFO['NO_FILE']
                return;
            }
            if (!ALLOWEB_TYPE[file.type]) {
                oInfo.innerText = UPLOAD_INFO['INVALID_TYPE']
                return;
            }
            const { name, size, type } = file;
            const fileName = new Date().getTime() + '_' + name;
            oProgress.max = size;
            oInfo.innerText = '';

            while (uploadedSize < size) {
                const fileChunk = file.slice(uploadedSize, uploadedSize + CHUNK_SIZE);
                const formData = createFormData({ name, size, type, fileName, uploadedSize, file: fileChunk });
                try {
                    uploadedResult = await axios.post(API, formData);
                } catch (e) {
                    oInfo.innerText = `${UPLOAD_INFO['UPLOAD_ERROR']} (${e.message})`;
                    return;
                }
                uploadedSize += fileChunk.size;
                oProgress.value = uploadedSize;
            }
            oInfo.innerText = UPLOAD_INFO['UPLOAD_SUCCESS'];
            oUploader.value = null;
            console.log(uploadedResult);
            createVedio(uploadedResult.data.video_url)
        };

        function createFormData({ name, size, type, fileName, uploadedSize, file }) {
            let formData = new FormData();
            formData.append('name', name);
            formData.append('size', size);
            formData.append('type', type);
            formData.append('fileName', fileName);
            formData.append('uploadedSize', uploadedSize);
            formData.append('file', file);
            return formData;
        }

        function createVedio (src) {
            const oVideo = doc.createElement('video');
            oVideo.controls = true;
            oVideo.autoplay = true;
            oVideo.width = '500';
            oVideo.src = src;

            doc.body.appendChild(oVideo);
        }
        init()
    })(document);